//
//  PCOpusDetailVC.m
//  PhotoCircle
//
//  Created by wujungao on 12/16/15.
//  Copyright © 2015 wujungao. All rights reserved.
//

#import "PCOpusDetailVC.h"
#import "PCUserGameModel.h"
#import "PCOpusDeatilStore.h"
#import "PCMeStore.h"
#import "PCGamePayController.h"
#import "PCUserModel.h"
#import "GMTipsHelper.h"
#import "UIImageView+WebCache.h"
#import "PCJoinPhotoMatchVC.h"

@interface PCOpusDetailVC ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic, strong)PCUserModel *userModel;
@property (weak, nonatomic) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet UIScrollView *scroll_backScrollView;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *lay_bottomViewHi;
@property (weak, nonatomic) IBOutlet UILabel *lab_worksName;//作品名称
@property (weak, nonatomic) IBOutlet UILabel *lab_worksContent;//作品简介
@property (weak, nonatomic) IBOutlet UILabel *lab_authorName;//作者名
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *lay_scrollViewConH;
@property (weak, nonatomic) IBOutlet UILabel *lab_status;
@property (weak, nonatomic) IBOutlet UIButton *btn_statusLeft;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *lay_leftBtnWi;
@property (weak, nonatomic) IBOutlet UIButton *btn_statusRight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *lay_rightBtnWi;
@property (weak, nonatomic) IBOutlet UIView *view_downView;

@property (nonatomic, strong) PCUserGameModel *gameModel;

@end

@implementation PCOpusDetailVC
{
    NSString *_status;
}

#pragma mark - VC method
- (void)viewDidLoad {
    [super viewDidLoad];
    self.scroll_backScrollView.hidden = YES;
    [self setBtnBorder:self.btn_statusLeft];
    [self setBtnBorder:self.btn_statusRight];
    [self loadData];
    self.view_downView.hidden = YES;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshGameDetail) name:@"refreshGameDetail" object:nil];
}

-(void)refreshGameDetail{
    
    [self loadData];
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self configNavAndTabBar];
}
- (void)setBtnBorder:(UIButton *)btn{
    [btn.layer setMasksToBounds:YES];
    [btn.layer setCornerRadius:btn.frame.size.height/2.0];
    [btn.layer setBorderWidth:1];
}
-(PCUserModel *)userModel{
    _userModel = [[PCUserInfoManager sharedUserInfo] readUserInfo];
    return _userModel;
}

#pragma mark - config views
-(void)configNavAndTabBar{
    
    MCShowNavBar();
    self.navigationController.navigationBar.translucent = NO;
    self.tabBarController.tabBar.hidden=YES;
}
- (void)resetThtDataWidthDataModel:(PCUserGameModel *)model{
    self.gameModel = model;
    self.lab_worksName.text = model.gTitle;
    if (model.gInfo.length==0) {
        self.lab_worksContent.text =@"暂无内容";
        [self resetBottomViewHiWidthString:@"暂无内容"];
    }else{
        self.lab_worksContent.text =model.gInfo;
        [self resetBottomViewHiWidthString:model.gInfo];
    }
    NSURL *url=[NSURL URLWithString:model.gImgUrl];
    [self.imageView sd_setImageWithURL:url placeholderImage:PCImage(@"")];
    self.lab_authorName.text = model.gAuthorName;
    _status =model.gState;
    [self configGameStates:model];
}

- (void)resetBottomViewHiWidthString:(NSString *)contentStr{
    NSString *test = contentStr;
    float worksContentHi =[self heightForString:test andWidth:(SCREEN_W-80)];
    CGFloat bottomViewHi = self.lab_worksContent.frame.origin.y +worksContentHi;
    self.lay_bottomViewHi.constant =bottomViewHi +20+16+10;
    self.lay_scrollViewConH.constant = bottomViewHi +20+16+20+45;
    [self.view layoutIfNeeded];
}

-(void)configGameStates:(PCUserGameModel *)gModel
{
    self.view_downView.hidden = NO;
    self.lab_status.text = gModel.gMarkGame;
    
    if ([gModel.gState isEqual:@"main_create"]){
        
        //self.lab_status.text = @"未付款";
        [self.btn_statusRight setTitleColor:PCColorC8 forState:UIControlStateNormal];
        [self.btn_statusRight.layer setBorderColor:PCColorC8.CGColor];
        [self.btn_statusLeft setTitleColor:PCColorC5 forState:UIControlStateNormal];
        [self.btn_statusLeft.layer setBorderColor:PCColorC5.CGColor];
        [self.btn_statusLeft setTitle:@"放弃参赛" forState:UIControlStateNormal];
        [self.btn_statusRight setTitle:@"待付款" forState:UIControlStateNormal];
        
    }else{
        
        self.btn_statusLeft.hidden = YES;
        self.lay_leftBtnWi.constant = 0;
        self.btn_statusRight.hidden = YES;
        self.lay_rightBtnWi.constant = 0;
    }
    
    [self.view layoutIfNeeded];
}

- (float)heightForString:(NSString *)value andWidth:(float)width{
    //获取当前文本的属性
    NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:value];
    NSRange range = NSMakeRange(0, attrStr.length);
    // 获取该段attributedString的属性字典
    NSDictionary *dic = [attrStr attributesAtIndex:0 effectiveRange:&range];
    // 计算文本的大小
    CGSize sizeToFit = [value boundingRectWithSize:CGSizeMake(width, MAXFLOAT) // 用于计算文本绘制时占据的矩形块
                                           options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading // 文本绘制时的附加选项
                                        attributes:dic        // 文字的属性
                                           context:nil].size; // context上下文。包括一些信息，例如如何调整字间距以及缩放。该对象包含的信息将用于文本绘制。该参数可为nil
    return sizeToFit.height + 22.0;
}

#pragma mark - button Action
- (IBAction)backBtnClick:(id)sender {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"refreshGameDetail" object:nil];
    [GMTipsHelper showDismiss];
    NSArray *vcs=[self.navigationController childViewControllers];
    UIViewController *vc;
    for(UIViewController *v in vcs){
        if([v isKindOfClass:[PCJoinPhotoMatchVC class]]){
            vc=v;
        }
    }
    
    if(vc){
        [self.navigationController popToViewController:vc animated:YES];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (IBAction)statusLeftBtnClick:(id)sender {
    
    //放弃参赛
    [self giveUpData];

}
- (IBAction)statusRightBtnClick:(id)sender {
    PCGamePayController *payVC = [PCGamePayController controllerInStoryboard:@"Main" identifier:@"PCGamePayControllerID"];
    [self.navigationController pushViewController:payVC animated:YES];
}
#pragma mark -加载页面数据
- (void)loadData;
{
    [GMTipsHelper showLoading];
    NSString *uuidStr;
    NSString *tokenStr;
    if (self.workUuid&&self.workUuid.length>0) {
        uuidStr= self.workUuid;
    }else{
        uuidStr = @"";
    }
    if (self.userModel.userToken&&self.userModel.userToken.length>0) {
        tokenStr= self.userModel.userToken;
    }else{
        tokenStr = @"";
    }
    NSDictionary *pDic = @{@"uuid":uuidStr,@"token":tokenStr};
    [[PCOpusDeatilStore sharedOpusDeatilStore] requestUserGameDataWith:pDic successHandler:^(id responseData){
        [GMTipsHelper showDismiss];
        if (responseData) {
            PCUserGameModel *dataModel = (PCUserGameModel *)responseData;
            [[PCMeStore sharedMeStore] selectedIndexGameModel:dataModel];
            self.scroll_backScrollView.hidden = NO;
            [self resetThtDataWidthDataModel:dataModel];
        }
    } otherCode:^(NSInteger code) {
        [GMTipsHelper showDismiss];
    } errorHandler:^{
        [GMTipsHelper showBadNetwork];
    }];
}

#pragma mark -放弃参赛
- (void)giveUpData{
    [GMTipsHelper showLoading];
    NSString *uuidStr;
    NSString *tokenStr;
    if (self.workUuid&&self.workUuid.length>0) {
        uuidStr= self.workUuid;
    }else{
        uuidStr = @"";
    }
    if (self.userModel.userToken&&self.userModel.userToken.length>0) {
        tokenStr= self.userModel.userToken;
    }else{
        tokenStr = @"";
    }
    NSDictionary *pDic = @{@"uuid":uuidStr,@"token":tokenStr};
    [[PCMeStore sharedMeStore]giveUpGame:pDic successHandler:^(NSInteger responCode, PCUserGameModel *gModel){
        if (responCode == API_RESPONSE_OK) {
            [GMTipsHelper showDismiss];
            self.gameModel = gModel;
            //  放弃参赛
            //_status = @"quit";
            [self configGameStates:self.gameModel];
        }else{
            [GMTipsHelper showFail:@"请求失败"];
        }
    } errorHandler:^{
        [GMTipsHelper showBadNetwork];
    }];
}

-(void)upLoadRealImage
{
    //相册上传
    UIImagePickerController *imagePickerVC=[[UIImagePickerController alloc] init];
    imagePickerVC.delegate=self;
    imagePickerVC.allowsEditing = YES;
    imagePickerVC.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:imagePickerVC animated:YES completion:nil];
}

#pragma mark - image picker delegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage];
    NSData *imgData = UIImageJPEGRepresentation(image, 1.0);
    NSString *uuidStr;
    NSString *tokenStr;
    if (self.workUuid&&self.workUuid.length>0) {
        uuidStr= self.workUuid;
    }else{
        uuidStr = @"";
    }
    if (self.userModel.userToken&&self.userModel.userToken.length>0) {
        tokenStr= self.userModel.userToken;
    }else{
        tokenStr = @"";
    }
    NSDictionary *dictionary = @{@"uuid":uuidStr,@"token":tokenStr};
    [GMTipsHelper showLoading];
    [[PCMeStore sharedMeStore] upLoadRealImage:dictionary image:imgData successHandler:^(NSInteger responCode){
        if (responCode == API_RESPONSE_OK) {
            [GMTipsHelper showSuccess:@"上传成功"];
            [self loadData];
        }else{
            [GMTipsHelper showFail:@"上传失败"];
        }
    } errorHandler:^{
        [GMTipsHelper showBadNetwork];
    }];
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
